package com.ad.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.common.model.ADModel;
import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.common.model.Admin;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;

import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.bjui.BjuiRender;
import com.jfaker.framework.security.model.*;
import com.jfaker.framework.security.web.validate.UserValidator;

public class ADController extends Controller {
	public static final String menuRel = "userList";
	
	  public void index(){
		   List<ADModel> ads = ADModel.dao.find("select * from ad");
		   setAttr("ads",ads);
		   System.out.println("得到数据"+ads.size()+"个");
		   render("list.jsp");
	   }
	  
	  public void getADJson(){
		  List<ADModel> ads = ADModel.dao.find("select * from ad");
		  List<ADModel> list = new ArrayList<ADModel>();
		 for(int i = 0;i<ads.size();i++){
			 ADModel ad = new ADModel();
			 ad.setId(ads.get(i).getLong("id"));
			 ad.setName(ads.get(i).getStr("name"));
			 ad.setAvatar_url(ads.get(i).getStr("avatar_url"));
			 ad.setPicture_url(ads.get(i).getStr("picture_url"));
			 ad.setKeyword(ads.get(i).getStr("keyword"));
			 ad.setText(ads.get(i).getStr("text"));
			 list.add(ad);
		 }
		  String json = JSON.toJSONString(list, true);	 
		  renderJson("{\"ads\": "+json+"}");
	  }
	   
	   public void form(){
		   Integer id = getParaToInt(0);
		   if(id!=null&&id>=0){
			   System.out.println(id+"tess"+ADModel.dao.findById(id).getStr("name"));
			 setAttr("ad",ADModel.dao.findById(id));
		   }
		   render("form.jsp");
	   }
	   
	   public void update(){
		   ADModel ad =  getModel(ADModel.class,"ad");
		   System.out.print("up"+ad.getStr("name"));
		   ad.update();
		   redirect("index");
	   }
	   
	   public void submit(){
		 ADModel ad =  getModel(ADModel.class,"ad");
		 System.out.print("up"+ad.getStr("name"));
		 ad.save();
	     System.out.println("result:list");
	      redirect("index");
	   }

	   
	   public void edit(){
		   form();
	   }
	   
	   public void del(){
		   ADModel.dao.deleteById(getPara(0));
		   redirect("/ad/index");
	   }
	   
	   public void login(){
		   render("login.html");
	   }
	   
	   /**
		 * 获取验证码
		 * @Description 
		 * @author hsongjiang
		 * @date 2016年2月9日 上午11:36:51
		 */
		public void getReadomCode(){
			renderCaptcha();
		}
		
		/**
		 * @category 实际登录
		 */
		public void dologin() {

			String error = "";
			String username = getPara("username", "").trim();
			String password = getPara("password", "").trim();
			if (!validateCaptcha("captcha")) {
				error = "验证码错误！";
				render(BjuiRender.error(error));
				return;
			}

			Admin user = null;

			// 1、判断用户名,密码是否为空
			if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
				error = "用户名或密码为空";
				render(BjuiRender.error(error));
				return;
			}
	
			user = Admin.dao.getBaseInfoByName(username);
		
			// 2、用户不存在，并且用户名不为数值,直接返回。
			if (user == null && !StringUtils.isNumeric(username)) {
				error = "帐号或密码有误";
				render(BjuiRender.error(error));
				
				return;
			}

			// 3、用户存在但被禁止
			if (user != null && !user.getBoolean("enabled")) {
				error = "用户被禁止";
				render(BjuiRender.error(error));
				return;
			}
			System.out.println("user4:"+username+password);

			// 获取用户相应权限及其session
			UsernamePasswordToken token=null;
			Subject subject = null;
			if (StringUtils.isEmpty(error)) {
				subject = SecurityUtils.getSubject();
				System.out.println("user5:"+username+password);
				token = new UsernamePasswordToken(username,password);//获取授权
				System.out.println("user3:"+username+password);
				try {
					subject.login(token);
				} catch (UnknownAccountException ue) {
					token.clear();
					error = "登录失败，您输入的账号不存在";
				} catch (IncorrectCredentialsException ie) {
					ie.printStackTrace();
					token.clear();
					error = "登录失败，密码不匹配";
				} catch (RuntimeException re) {
					re.printStackTrace();
					token.clear();
					error = "登录失败";
				}
			}
			if (StringUtils.isEmpty(error)) {
				new Admin().set("id", user.getInt("id")).set("online", 1)
						.set("logintime", new Date()).update();
				
				if(getParaToBoolean("remember")){ //如果是记住密码，那么下次自动登录
					token.setRememberMe(true);
				}
				render(BjuiRender.success("登录成功！"));
			} else {
				render(BjuiRender.error(error));
				return;
			}
		}
		
		//注册页面
		public void add() {
			setAttr("roles", Role.dao.getAll());
			setAttr("p_org", Org.dao.getList());
			render("userAdd.html");
		}
		
		//保存注册内容
//		public void save(){
//			 render("list.jsp");
//		}
		/**
		 * 后台添加用户，其中部门只能手写。 添加用户，有个大前提：部门中一定要有家长和教师。家长用于本系统的所有家长部门，而教师下面是各个单位。
		 * 
		 * @author hsongjiang 2015-03-03
		 */
		@Before({ UserValidator.class, Tx.class })
		public void save() {
			Integer[] orderIndexs = getParaValuesToInt("orderIndexs");
			Integer groupid = getParaToInt("user.grouptype", 0);
			//
			if (getPara("user.nickname").trim().length() < 2) {
				render(BjuiRender.error("昵称过短"));
				return;
			}
			Admin muser = Admin.dao
					.getBaseInfoByName(getPara("user.username").trim());

			if (muser != null) {
				render(BjuiRender.error("用户名已经存在"));
				return;
			}

			Admin memail = Admin.dao.getBaseInfoByEmail(getPara("user.email").trim());
			if (memail != null) {
				render(BjuiRender.error("邮箱已经被注册了"));
				return;
			}

			Admin user = new Admin().set("grouptype", groupid)
					.set("realname", getPara("user.realname"))
					.set("nickname", getPara("user.nickname"))
					.set("email", getPara("user.email"))
					.set("username", getPara("user.username"))
					.set("plainPassword", getPara("user.plainPassword"))
					.set("gender", getParaToInt("user.gender", 0))
					.set("regtime", new Date());
			user.entryptPasswordWithSalt(getPara("user.plainPassword")); // 加密密码
			user.save();

			if (orderIndexs != null) {
				for (Integer orderIndex : orderIndexs) {
					Admin.dao.insertCascade(user.getInt("id"), orderIndex);
				}
			}
			render(BjuiRender.closeCurrentAndRefresh(menuRel));
		}
}
